import React, { Component } from 'react'

// 引入store 用于获取redux中的数据
import store from '../../redux/store'

export default class CountReduxEx extends Component {

    increment = () => {
        const { value } = this.selectNumber
        store.dispatch({
            type: 'increment',
            data: parseInt(value)
        })
    }

    decrement = () => {
        const { value } = this.selectNumber
        store.dispatch({
            type: 'decrement',
            data: parseInt(value)
        })
    }

    incrementIfOdd = () => {
        const { value } = this.selectNumber

        if (store.getState() % 2 !== 0) {
            store.dispatch({
                type: 'increment',
                data: parseInt(value)
            })
        }
    }

    incrementIfEvent = () => {
        const { value } = this.selectNumber

        if (store.getState() % 2 == 0) {
            store.dispatch({
                type: 'increment',
                data: parseInt(value)
            })
        }
    }

    incrementAsync = () => {
        const { value } = this.selectNumber

        setTimeout(() => {
            store.dispatch({
                type: 'increment',
                data: parseInt(value)
            })
        }, 1000)
    }

    render() {
        return (
            <div>
                <h1>redux实现count组件</h1>
                {/* store.getState()表示获取store中的状态 */}
                <h1>当前求和为:{store.getState()}</h1>
                <select ref={c => { this.selectNumber = c }}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
                <button onClick={this.increment}>+</button>
                <button onClick={this.decrement}>-</button>
                <button onClick={this.incrementIfOdd}>当前求和为奇数在加</button>
                <button onClick={this.incrementIfEvent}>当前求和为偶数在加</button>
                <button onClick={this.incrementAsync}>当前求和为偶数在加</button>
            </div>
        )
    }
}
